package com.cloud.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.mapper.FileMapper;
import com.cloud.mapper.UserMapper;
import com.cloud.pojo.User;
import com.cloud.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 上传文件表 服务实现类
 * </p>
 *
 * @author haoyeee123
 * @since 2022-01-15
 */
@Service
public class FileServiceImpl implements FileService {
    //定义文件上传的根路径
    private String rootDir = "D:/fileCloud/flies";
    private String rootUrl = " http://file.cloud.com";
    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private UserMapper userMapper;
    //设定最大下载次数
    Integer maxDownloads = 2;

    /**
     * 上传文件
     */
    @Override
    public void addFile(Integer uid, MultipartFile file) {
        //获取文件名称
        String fileName = file.getOriginalFilename().toLowerCase();
//        //校验文件名称
//        if (!fileName.matches("^.+\\.(jpg|png|gif)$")){
//            return;
//        }
        try {
            //分目录存储
            String datePath = new SimpleDateFormat("/yyyy/MM-dd/").format(new Date());
            String fileDir = rootDir + datePath;
            File dirFile = new File(fileDir);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            //动态生成UUID
            String UUID = java.util.UUID.randomUUID().toString();
            int index = fileName.lastIndexOf(".");
            String fileType = fileName.substring(index);
            String fileHashName = UUID + fileType;
            //实现文件上传到本地
            String path = fileDir + fileHashName;
            file.transferTo(new File(path));
            //获取文件大小
            long size = file.getSize();
            //动态路径为pathUrl
            String virtualPath = datePath + fileHashName;
            //动态网络路径
            String urlPath = rootUrl + virtualPath;
            //文件上传到数据库
            com.cloud.pojo.File fileDB = new com.cloud.pojo.File();
            fileDB.setFileName(fileName);
            fileDB.setHashName(fileHashName);
            fileDB.setUploadTime(new Date());
            fileDB.setType(fileType);
            fileDB.setDownload(0);
            fileDB.setUid(uid);
            fileDB.setSize(String.valueOf(size));
            fileDB.setFileUrl(virtualPath);
            fileMapper.insertFile(fileDB);
        } catch (Exception e) {
            throw new RuntimeException();
        }

    }

    /**
     * 获取文件列表
     */
    @Override
    public List<com.cloud.pojo.File> getList(com.cloud.pojo.File file) {
        QueryWrapper<com.cloud.pojo.File> queryWrapper = new QueryWrapper();
        queryWrapper.eq("uid", file.getUid());
        List<com.cloud.pojo.File> files = fileMapper.selectList(queryWrapper);
        return files;
    }

    /**
     * 文件下载
     */
    @Override
    public void getFile(HttpServletRequest request, HttpServletResponse response, com.cloud.pojo.File file) {
        file = fileMapper.selectById(file.getId());
        //下载次数判断
        Integer uid = file.getUid();
        User user = userMapper.selectById(uid);
        Integer vip = user.getVip();
        Integer downloads = file.getDownload();
        if (vip == 0 && downloads > maxDownloads) {
            response.setContentType("text/html;charset=utf-8");
            try {
                PrintWriter out = response.getWriter();
                out.println("<h2>下载次数受到限制,请开通会员</h2>");
                out.flush();
                out.close();
            } catch (Exception e) {
                throw new RuntimeException();
            }
            return;
        }
        //获取真实路径
        String filePath = rootDir + file.getFileUrl();
        FileInputStream fileInputStream = null;
        try {
            File file2 = new File(filePath);
            if (!file2.exists()) {
                throw new FileNotFoundException(filePath);
            }
            // 获取输入流 用于读取文件
            fileInputStream = new FileInputStream(new java.io.File(filePath));
            //获取文件类型
            String type = file.getType();
            type = type.split("\\.")[1];
            //设置响应类型，根据前端传递数据类型设置响应类型
            response.setContentType(request.getSession().getServletContext().getMimeType(type));
            //设置响应头，attachment表示以附件的形式下载，inline表示在线打开
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(file.getFileName(), "UTF-8"));
            //获取输出流对象（用于写文件）
            ServletOutputStream outputStream = response.getOutputStream();
            //下载文件,使用spring框架中的FileCopyUtils工具
            FileCopyUtils.copy(fileInputStream, outputStream);

            //增加下载次数
            downloads++;
            file.setDownload(downloads);
            fileMapper.updateById(file);
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
//    private boolean selectDownloads(Integer uid){
//        User user = userMapper.selectById(uid);
//        Integer vip = user.getVip();
//        if (vip==1){
//            return true;
//        }
//        if (vip==0){
//            return false;
//        }
//        return true;
//    }

    /**
     * 文件删除
     */
    @Override
    public void deleteFile(com.cloud.pojo.File file) {
        fileMapper.deleteById(file.getId());
        String filePath = rootDir + file.getFileUrl();
        File file1 = new File(filePath);
        file1.delete();
    }


}
